package com.yunduo.world.utils;

import com.yunduo.world.constant.NetWorkConstant;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端连接
 */
@Slf4j
@Component
public class ClientUtils{
    private static ConcurrentHashMap<Channel,String> clients = new ConcurrentHashMap<>();

    /**
     * 关闭通道,关闭客户端
     * @param channel
     * @return
     */
    public static boolean removeChannel(Channel channel) {
        String id = clients.get(channel);
        NetRoomUtils.deleteRoom(id);
        clients.remove(channel);
        channel.close();
        log.info("用户已下线"+id);
        return true;
    }

    public static String get(Channel channel) {
        return clients.get(channel);
    }

    public static Channel get(String id){
        for (Map.Entry<Channel, String> client:entrySet()){
            if (client.getValue().equals(id)){
                return client.getKey();
            }
        }
        return null;
    }

    public static boolean put(Channel channel,String id) {
        clients.put(channel,id);
        return true;
    }

    public static Set<Map.Entry<Channel, String>> entrySet(){
        return clients.entrySet();
    }
}
